package routers

import (
	"bytes"
	"context"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/route"
	"hertz/api"
	"hertz/pojo"
	myUtils "hertz/utils"
	"io"
	"mime/multipart"
	"time"
)

func loadVideo(h *route.RouterGroup) {
	h.GET("/feed", feed)
	video := h.Group("/publish")
	{
		video.POST("/action/", addVideo)
		video.GET("/list/", getVideoList)
	}
}

func feed(_ context.Context, ctx *app.RequestContext) {
	videoAction := myUtils.GetParamVideo(ctx)

	// 不鉴权
	user, _ := userProvider.Authenticate(context.Background(), &api.Token{
		Token:     videoAction.Token,
		Operation: "*",
	})

	videoList, err := videoProvider.GetVideoRecently(context.Background(), &api.Video{
		CreateTime: transInt64(videoAction.LatestTime),
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	// 转换对象
	var list []pojo.Video
	for _, value := range videoList.GetList() {
		list = append(list, transVideo(user, value))
	}

	var nextTime int64
	if len(list) > 0 {
		nextTime = list[len(list)-1].CreateTime
	} else {
		nextTime = time.Now().Unix()
	}
	OK(ctx, utils.H{"video_list": list, "next_time": nextTime})
}

func addVideo(_ context.Context, ctx *app.RequestContext) {
	// 鉴权
	user, err := userProvider.Authenticate(context.Background(), &api.Token{
		Token:     ctx.PostForm("token"),
		Operation: "*",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	formFile, err := ctx.FormFile("data")
	if err != nil {
		FAIL(ctx, err)
		return
	}
	open, err := formFile.Open()
	defer func(open multipart.File) {
		err := open.Close()
		if err != nil {

		}
	}(open)
	buff := new(bytes.Buffer)
	_, _ = io.Copy(buff, open)

	// 传输视频
	_, err = videoProvider.AddVideo(context.Background(), &api.Video{
		UserId: user.Id,
		Title:  ctx.PostForm("title"),
		Data:   buff.Bytes(),
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	OK(ctx, nil)
}

func getVideoList(c context.Context, ctx *app.RequestContext) {
	videoAction := myUtils.GetParamVideo(ctx)

	// 不鉴权
	user, _ := userProvider.Authenticate(context.Background(), &api.Token{
		Token:     videoAction.Token,
		Operation: "GET_VIDEO_LIST",
	})

	videoList, err := videoProvider.GetVideoByUserId(context.Background(), &api.Video{UserId: user.GetId()})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	// 转换对象
	var list []pojo.Video
	for _, value := range videoList.GetList() {
		list = append(list, transVideo(user, value))
	}

	OK(ctx, utils.H{"video_list": list})
}
